<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <script>
        var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
            CSS.supports('top: constant(a)'))
        document.write(
            '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
            (coverSupport ? ', viewport-fit=cover' : '') + '" />')
    </script>
    <title>微信支付</title>
    <style type="text/css">
        #app{
            height: 98vh;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        #tip{
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
        }
        .loading {
            width: 96px;
            height: 96px;
            display: inline-block;
            vertical-align: middle;
            animation: e 1s steps(12) infinite;
            background: url() no-repeat;
            background-size: 100%;
        }
        @keyframes e {
            0% {
                transform: rotate(0deg)
            }

            to {
                transform: rotate(1turn)
            }
        }
    </style>
</head>

<body>
<div id="app">
    <div id="tip">正在获取授权</div>
    <i class="loading"></i>
</div>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>
    function toPay() {
        document.getElementById('tip').innerHTML = '正在发起支付...'
        let token = localStorage.getItem("token")
        let order_no = localStorage.getItem("order_no")
        let baseUrl = localStorage.getItem("baseUrl")
        let requestUrl = `${baseUrl}/api/payment`
        $.ajax({
            url: requestUrl,
            headers: {
                'Authorization': 'Bearer ' + token
            },
            type: 'POST',
            dataType: "JSON",
            contentType: "application/json",
            data: JSON.stringify({
                channel: 'adapay',
                method: 'wx_pub',
                orderNo: order_no,
                subject: '充值',
                body: '',
                wx_code: wxUserCode,
                amount:1
            }),
            success: function (data) {
                if (data.code == 0) {
                    document.getElementById('tip').innerHTML = '正在支付'
                    let payObj = JSON.parse(data.data.url)
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId": payObj.appId,     //公众号ID，由商户传入
                            "timeStamp": payObj.timeStamp,         //时间戳，自1970年以来的秒数
                            "nonceStr": payObj.nonceStr, //随机串
                            "package": payObj.package,
                            "signType": payObj.signType,         //微信签名方式：
                            "paySign": payObj.paySign //微信签名
                        },
                        function (res) {
                            if (res.err_msg == "get_brand_wcpay_request:ok") {
                                document.getElementById('tip').innerHTML = '支付成功！！！'
                            } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                                document.getElementById('tip').innerHTML = '支付失败！！！'
                            } else {
                                document.getElementById('tip').innerHTML = '取消支付！！！'
                            }
                        });
                }else {
                    document.getElementById('tip').innerHTML = data.msg
                }
            },
            error:function(){
                document.getElementById('tip').innerHTML = '请求错误，请重试！！！'
            }
        });
    }
    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
        var context = "";
        if (r != null)
            context = decodeURIComponent(r[2]);
        reg = null;
        r = null;
        return context == null || context == "" || context == "undefined" ? "" : context;
    }
    let wxUserCode = GetQueryString("code");
    let appId = GetQueryString("appId")
    let redirectUrl = encodeURIComponent(`${GetQueryString("baseUrl")}/adapay/wxpay.html`);
    if (GetQueryString("token")) {
        localStorage.setItem("token", GetQueryString('token'))
    }
    if (GetQueryString("baseUrl")) {
        localStorage.setItem("baseUrl", GetQueryString('baseUrl'))
    }
    if (GetQueryString('order_no')) {
        localStorage.setItem("order_no", GetQueryString('order_no'))
    }
    if (!wxUserCode) {
        // 没有微信code，跳转去获取
        if(appId){
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base`;
        }else{
            document.getElementById('tip').innerHTML = '参数错误,Appid不存在！！！'
        }
    } else {
        toPay()
    }
</script>
</body>

</html>
